<template>
  <view class="userbtn-module">
    <view class="userbtn-module_title">
      <text>我的服务</text>
    </view>
    <view class="userbtn-module_list">
      <template v-for="(v, i) in myService" :key="i">
        <view v-if="v.show" class="userbtn-module_item" @click="v.fnc?.()">
          <button v-if="v.shareId" open-type="share" class="share-btn" :id="v.shareId" />
          <view
            v-if="v.icon.includes('icon')"
            :class="['ant-iconfont', v.icon]"
            :style="{ color: globalConfig?.themeColor }"
          ></view>
          <view v-else class="ali-icon" :style="{ color: globalConfig?.themeColor }">
            {{ v.icon }}
          </view>
          <view class="userbtn-module_item--text">{{ v.text }}</view>
          <view v-if="v.badgeNum" :class="['badge-dot', v.badgeNum > 99 && 'badge-dot__max']">
            <text>{{ v.badgeNum > 99 ? '99+' : v.badgeNum }}</text>
          </view>
        </view>
      </template>
    </view>
  </view>
  <view v-if="sysUserId" class="userbtn-module">
    <view class="userbtn-module_title">
      <text>我的管理</text>
    </view>
    <view class="userbtn-module_list">
      <template v-for="(v, i) in myManager" :key="i">
        <view v-if="v.show" class="userbtn-module_item" @click="v.fnc?.()">
          <button v-if="v.shareId" open-type="share" class="share-btn" :id="v.shareId" />
          <!-- <image class="userbtn-module_item--icon" :src="iconBaseUrl + v.icon" /> -->
          <view
            v-if="v.icon.includes('icon')"
            :class="['ant-iconfont', v.icon]"
            :style="{ color: globalConfig?.themeColor }"
          ></view>
          <view v-else class="ali-icon" :style="{ color: globalConfig?.themeColor }">
            {{ v.icon }}
          </view>
          <view class="userbtn-module_item--text">{{ v.text }}</view>
          <view v-if="v.badgeNum" :class="['badge-dot', v.badgeNum > 99 && 'badge-dot__max']">
            <text>{{ v.badgeNum > 99 ? '99+' : v.badgeNum }}</text>
          </view>
        </view>
      </template>
    </view>
  </view>
  <ShowModal
    v-model="modalVisible"
    :title="modalTitle"
    :showCancel="false"
    openType="share"
    :confirm-text="confirmText"
    :Share_ButtonId="modalShareButtonId"
  >
    <template #content>
      <div class="pa-15">
        <template v-if="modalShareButtonId === ShareButtonId.COLLECTINGDATA">
          <div>分享本链接到微信好友或者微信群，可用于收集入会资料：</div>
          <div class="disFlx">
            <div style="flex-shrink: 0" class="pr-3">1.</div>
            <div>如果系统没有该用户的资料，进入入会申请流程；</div>
          </div>
          <div class="disFlx">
            <div style="flex-shrink: 0" class="pr-3">2.</div>
            <div>如果系统已存在该用户资料，可更新或者补充资料。</div>
          </div>
        </template>
        <template v-else>
          <div class="disFlx">
            <div style="flex-shrink: 0" class="pr-3">1.</div>
            <div>分享本链接到微信好友或者微信群，可用于完善名片资料；</div>
          </div>
          <div class="disFlx">
            <div style="flex-shrink: 0" class="pr-3">2.</div>
            <div>名片完善度越高，越有利于人脉资源交流。</div>
          </div>
        </template>
      </div>
    </template>
  </ShowModal>
</template>

<script setup lang="ts">
  import { navigateTo } from '@/router';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { computed, ref, type Ref } from 'vue';
  import { storeToRefs } from 'pinia';
  import ShowModal from '@/components/ShowModal/index.vue';
  import { ShareButtonId } from '@/enums/shareEnum';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { isLogin } from '@/utils/is';
  import { onPullDownRefresh, onShow } from '@dcloudio/uni-app';
  import { sysAuditStatistics } from '@/api/admin';
  import { authOfficialAccount } from '@/utils';
  import { getQrcodeInstitutionInfo } from '@/api/cooperation';
  import { toHuibangCloud } from '@/utils/dynamicConfig';
  import type { EmitShowCustomShareType } from '../utils';
  import { getUserStatistics } from '@/api/mine';

  interface BtnItem {
    icon: string;
    text: string;
    show: boolean | Ref;
    fnc: () => void;
    shareId?: ShareButtonId;
    type?: 'card' | 'resource';
    badgeNum?: number | Ref<number>;
  }

  const useUser = useUserStoreWithOut();
  const { globalConfig } = useAppStoreWithOut();
  const { currentCocId, userInfo, cocInfo } = storeToRefs(useUser);
  const sysUserId = computed(() => userInfo.value.sysUserId);
  const getPhonenumber = computed(() => userInfo.value.phonenumber);

  // const emits = defineEmits<{
  //   /** invite 邀请入会  relevancy 公众号关联  */
  //   (e: 'showCustomShare', type: EmitShowCustomShareType): void;
  // }>();

  const modalVisible = ref(false);
  const modalTitle = ref('会员资料收集');
  const confirmText = ref('分享收集会员资料');
  const modalShareButtonId = ref(ShareButtonId.COLLECTINGDATA);
  const contactsUnlockAuditNumber = ref(0);
  const memberAuditNumber = ref(0);
  const activityWaitAuditNumber = ref(0);
  const boWaitAuditNumber = ref(0);
  /** 供需小红点 */
  const boNum = ref(0);
  /** 群聊小红点 */
  const msgNum = ref(0)

  const myService = ref<BtnItem[]>([
    {
      icon: 'icon-huodong',
      text: '我的活动',
      show: true,
      fnc: () => {
        isLogin(() => navigateTo({ name: 'myActivity' }));
      },
    },
    {
      icon: 'icon-qunliao',
      text: '我的消息',
      badgeNum: msgNum,
      show: true,
      fnc: () => {
        isLogin(() => navigateTo({ name: 'TUIConversation' }));
      },
    },
    {
      icon: 'icon-map',
      text: '我的人脉',
      show: true,
      fnc: () => {
        isLogin(() => {
          useUser.validatePerfectionInfo().then(() => {
            navigateTo({ name: 'myContactList' });
          });
        });
      },
    },
    {
      icon: 'icon-dingdan',
      text: '我的订单',
      show: true,
      fnc: () => {
        isLogin(() => navigateTo({ name: 'myOrder' }));
      },
    },
    {
      icon: '\ue6cc',
      text: '我的供需',
      show: true,
      badgeNum: boNum,
      fnc: () => {
        isLogin(() =>
          navigateTo({
            name: 'myBusinessOpportunities',
            options: {},
          }),
        );
      },
    },
    {
      icon: 'icon-fuwu',
      text: '政策服务',
      show: currentCocId,
      fnc: () => {
        isLogin(() =>
          navigateTo({ name: 'policyServiceReport', options: { name: cocInfo.value.cocName } }),
        );
      },
    },
    {
      icon: 'icon-fuli',
      text: '我的福利',
      show: true,
      fnc: () => {
        isLogin(() => navigateTo({ name: 'memberCoupon' }));
      },
    },
    {
      icon: 'icon-ruhui',
      text: '入会资料',
      show: currentCocId,
      fnc: () => navigateTo({ name: 'updateMembershipInfo' }),
    },
    {
      icon: 'icon-chengyuan',
      text: '成员管理',
      show: currentCocId,
      fnc: () => navigateTo({ name: 'membershipManage', options: {} }),
    },
    {
      icon: '\ue633',
      text: '资源平台',
      show: computed(() => currentCocId.value && userInfo.value.isOpenMall),
      fnc: () => toMall(),
    },
    // {
    //   icon: 'icon-yaoqing',
    //   text: '邀请入会',
    //   show: getPhonenumber,
    //   fnc: async function () {
    //     emits('showCustomShare', 'invite');
    //   },
    // },
    // {
    //   icon: 'user-icon-8.png',
    //   text: '单位主页',
    //   show: currentCocId && isUnit.value,
    //   fnc: toUnitCard,
    // },
    // {
    //   icon: 'icon-guanzhu',
    //   text: '公众号关联',
    //   show: getPhonenumber,
    //   // shareId:
    //   //   userInfo.value.isOfficialAccount !== IsOfficialAccountEnum.UNKNOWN
    //   //     ? ShareButtonId.ATTENTION
    //   //     : void 0,
    //   fnc: async () => {
    //     try {
    //       await authOfficialAccount();
    //     } catch (error) {}
    //     emits('showCustomShare', 'relevancy');
    //   },
    // },
    {
      icon: '\ue6ab',
      text: '表单记录',
      show: true,
      fnc: () => {
        navigateTo({
          name: 'appServiceFormRecord',
        });
      },
    },
  ]);

  const myManager = ref<BtnItem[]>([
    {
      icon: 'icon-huiyuan',
      text: '会员管理',
      show: useUser.checkRouterPermission('memberManage'),
      fnc: () => navigateTo({ name: 'memberManage' }),
    },
    {
      icon: '\ue6b0',
      text: '活动管理',
      show: useUser.checkRouterPermission('activityManage'),
      fnc: () => {
        navigateTo({
          name: 'activityManage',
        });
      },
      badgeNum: activityWaitAuditNumber,
    },
    {
      icon: '\ue6cc',
      text: '供需管理',
      show: true,
      fnc: () => navigateTo({ name: 'businessOpportunitiesManage' }),
      badgeNum: boWaitAuditNumber,
    },
    {
      icon: 'icon-shenhe',
      text: '会员审核',
      show: useUser.checkRouterPermission('memberAudit'),
      fnc: () => navigateTo({ name: 'memberAudit' }),
      badgeNum: memberAuditNumber,
    },
    {
      icon: '\ue61b',
      text: '缴费管理',
      show: useUser.checkRouterPermission('paymentManagement'),
      fnc: () => navigateTo({ name: 'paymentManagement' }),
    },
    {
      icon: 'icon-mingpian',
      text: '收集名片',
      show: true,
      // shareId: ShareButtonId.COLLECTINGCARD,
      type: 'card',
      fnc: () => {
        modalVisible.value = true;
        modalTitle.value = '名片资料收集';
        confirmText.value = '分享收集名片';
        modalShareButtonId.value = ShareButtonId.COLLECTINGCARD;
      },
    },
    {
      icon: 'icon-ziliao',
      text: '收集资料',
      show: true,
      // shareId: ShareButtonId.COLLECTINGDATA,
      type: 'resource',
      fnc: () => {
        modalVisible.value = true;
        modalTitle.value = '会员资料收集';
        confirmText.value = '分享收集会员资料';
        modalShareButtonId.value = ShareButtonId.COLLECTINGDATA;
      },
    },
    {
      icon: '\ue67a',
      text: '相册管理',
      show: useUser.checkRouterPermission('photosManagement'),
      fnc: () => navigateTo({ name: 'photosManagement' }),
    },
    {
      icon: '\ue62a',
      text: '消息管理',
      show: useUser.checkRouterPermission('messageManagement'),
      fnc: () => navigateTo({ name: 'messageManagement' }),
    },
    {
      icon: 'icon-renmai1',
      text: '人脉审核',
      show: useUser.checkRouterPermission('contactReview'),
      fnc: () => navigateTo({ name: 'contactReview' }),
      badgeNum: contactsUnlockAuditNumber,
    },
    {
      icon: 'icon-danwei',
      text: '合作管理',
      show: useUser.checkRouterPermission('cooperationList'),
      fnc: () => navigateTo({ name: 'cooperationList' }),
    },
    {
      icon: '\ue628',
      text: '扫码合作',
      show: useUser.checkRouterPermission('applyCooperation'),
      fnc: () => {
        uni.scanCode({
          success: (res) => {
            getQrcodeInstitutionInfo(res.result).then((r) => {
              uni.setStorageSync('_CLICK_INFO', r);
              navigateTo({ name: 'applyCooperation' });
            });
          },
        });
      },
    },
    {
      icon: 'icon-fangke',
      text: '意向会员',
      show: useUser.checkRouterPermission('intendedMembers'),
      fnc: () => navigateTo({ name: 'intendedMembers' }),
    },
    {
      icon: '\ue633',
      text: '资源平台',
      show: userInfo.value.isOpenMall,
      fnc: () => toMall(),
    },
    {
      icon: '\ue6ab',
      text: '服务表单',
      show: useUser.checkRouterPermission('serviceForm'),
      fnc: () => {
        navigateTo({ name: 'serviceForm' });
      },
    },
    {
      icon: '\ue6a9',
      text: '下载记录',
      show: true,
      fnc: () => {
        navigateTo({ name: 'exportRecord' });
      },
    },
  ]);

  function toUnitCard() {
    navigateTo({ name: 'businessCard', options: { id: currentCocId.value as number } });
  }

  const isInit = ref(false);
  getSysAuditStatistics();
  queryUserStatistics();

  onShow(() => {
    if (isInit.value) {
      queryUserStatistics();
      getSysAuditStatistics();
    }
  });

  onPullDownRefresh(() => {
    getSysAuditStatistics();
  });

  function getSysAuditStatistics() {
    if (userInfo.value.phonenumber && userInfo.value.sysUserId) {
      sysAuditStatistics().then((r) => {
        isInit.value = true;
        contactsUnlockAuditNumber.value = r.contactsUnlockAuditNumber;
        memberAuditNumber.value = r.memberAuditNumber;
        activityWaitAuditNumber.value = r.activityWaitAuditNumber;
        boWaitAuditNumber.value = r.boWaitAuditNumber;
      });
    }
  }

  async function queryUserStatistics() {
    const res = await getUserStatistics();
    boNum.value = res.boNum;
    msgNum.value = res.msgNum
  }

  async function toMall() {
    toHuibangCloud('storeHome', { type: 'mine' });
  }
</script>

<style lang="scss" scoped>
  .userbtn-module {
    background-color: #fff;
    border-radius: 16rpx;
    min-height: 154rpx;
    position: relative;
    padding: 0 30rpx;
    margin-bottom: 30rpx;
    &_title {
      padding: 30rpx 0;
      color: #333;
      font-size: 28rpx;
      font-weight: bolder;
    }
    &_list {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }

    &_item {
      width: 25%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      color: #333;
      font-size: 28rpx;
      position: relative;
      margin-bottom: 30rpx;
      .badge-dot {
        position: absolute;
        top: -10rpx;
        right: 20%;
        width: 44rpx;
        height: 44rpx;
        background-color: #ea5e0e;
        color: #fff;
        border-radius: 50%;
        text-align: center;
        line-height: 44rpx;
        font-size: 24rpx;
        box-shadow: 2rpx 2rpx 2rpx 0px rgba(0, 0, 0, 0.2);
        &__max {
          border-radius: 24rpx;
          width: auto;
          padding: 0 8rpx;
        }
      }

      .share-btn {
        width: 100%;
        height: 100%;
        opacity: 0;
        position: absolute;
        left: 0;
        top: 0;
      }

      .ant-iconfont,
      .ali-icon {
        font-size: 65rpx;
        margin-bottom: 10rpx;
      }
    }
  }
</style>
@/components/CustomShare/types
